<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/component/commonTagLib.jsp" %>

<!DOCTYPE html>
<html>
<head>
	<title>调价计划明细</title>
	<%@ include file="/WEB-INF/component/commonCSS.jsp" %>
</head>
<body class="skin-blue-light sidebar-mini fixed skin-blue-light-frame">
    <section class="content-header">
        <h1>调价计划明细</h1>
        <ol class="breadcrumb">
            <li><a href="${ctx}/home.jsp"><i class="fa fa-home"></i>首页</a></li>
			<li class="active"><a href="#">交易</a></li>
			<li class="active"><a href="#">药品调价</a></li>
            <li class="active"><a href="#">未处理调价计划</a></li>
        </ol>
    </section>
    
    <section class="content">
        <div class=" box box-success">
            <div class="box-body">
            	<div class="input">
            	   <div class="textalign1">通用名：</div>
                    <div class="boxinput">
                        <input id="drugName"  class="textinput" type="text" placeholder="通用名" />
                    </div>
            	
            		<div class="textalign">药品编码：</div>
            		<div class="boxinput">
            			<input id="drugCode" class="textinput" type="text" placeholder="药品编码" />
            		</div>
            		
            		<div class="textalign">生产企业：</div>
            		<div class="boxinput">
            			<input id="prodComp" class="textinput" type="text" placeholder="生产企业" />
            		</div>
            	
            	</div>
            	<div class="input">
                   
                    <div class="textalign1">项目名称：</div>
                    <div class="boxinput">
                        <input id="projName" class="textinput" type="text" placeholder="项目名称" />
                    </div>
                
                    <div class="textalign">
                        <button type="button" class="btn btn-success btn-sm" onclick="search();" id="selectc">查&nbsp;询 </button>
                    </div>
                </div>
            </div>
        </div>

        <table class="jqgrid" id="gridlist"></table>
        <div id="gridpage"></div>
        <div class=" box box-warning bottongroup">
        	<a href="toPricePlanAddDrug.html?id=${pricePlan.priceAdjPlanId}" class="btn btn-primary btn-sm">添&nbsp;加</a>
            <label id="save" class="btn btn-primary btn-sm" onclick="batchEditDrug();">保&nbsp;存</label>
   			<label id="make" class="btn btn-primary btn-sm" onclick="runChangePlan();">执&nbsp;行</label>
   			<label id="batchDelete" class="btn btn-danger btn-sm" onclick="batchDeleteDrug();">删&nbsp;除</label>
   			<a href="toUnChangePlan.html" class="btn btn-danger btn-sm">返&nbsp;回</a>
        </div>

    </section>
    <%@ include file="/WEB-INF/component/commonJS.jsp" %>
    <script type="text/javascript">
    

	 //绑定回车
   $('#goodsCode,#drugName,#prodComp,#drugCode,#projName').bind('keydown', function(event) {
       if (event.keyCode == "13") {        //13 位电脑上回车键的位置代码
           $('#selectc').click();
       }
   }); 
   
   $("#goodsCode").focus();//加载页面光标在第一个查询框上
   
    var sta = 0;
		function search(page) {
			var goodsCode = $.trim($("#goodsCode").val());
			var drugCode = $.trim($("#drugCode").val());
			var drugName = $.trim($("#drugName").val());
			var prodComp = $.trim($("#prodComp").val());
			var projName = $.trim($("#projName").val());
			$("#gridlist").jqGrid('setGridParam',{  
				mtype: "POST",
		        datatype:'json',
		        postData:{"goodsCode":goodsCode, "drugCode":drugCode, "drugName":drugName, "prodComp":prodComp,"projName":projName},
		        page : (page || 1)
		    }).trigger("reloadGrid"); //重新载入  
		}
		function runChangePlan(type) {
			//var type = "${pricePlan.executeCat}";  
			var rowIds = $("#gridlist").jqGrid("getDataIDs")||[];
			if (rowIds.length <= 0) {
				$.HN.message.alert("请您添加调价明细！", "消息", "warn");
				return;
			}
			if(sta==1){
				$.HN.message.alert("请您先保存！", "消息", "warn");
				return;
			}
			//var tips = type == "2" ? "当前计划为自动执行计划，您确定立即执行吗？" : "您确定立即执行吗？";
			$.HN.message.confirm("将为您执行所有的调价明细", "提示信息", "确定").on(function(bool) {
				if (bool) {
					$.ajax({
						type:"POST",
						url:"runChangePlan.html",
						data:{"planId":"${pricePlan.priceAdjPlanId}"},
						dataType:"json",
						success:function(returnData){
							if (returnData.success != false) {
								$.HN.message.alert("为您执行成功！", "消息", "success", function() {
									document.location = "${ctx}/basePriceadjplan/toDataListJsp.html";
								});
			    			} else {
			    				$.HN.message.alert("操作失败！", "消息", "error");
			    			}
						},
						error:function() {
							top.window.document.location = "${ctx}/login.html";
						}
					});
				}
			});
		}
		
		
		$(function () {
        	//列表
            $("#gridlist").jqGrid({
                url: "getPriceDurgList.html",
                mtype: "POST",
                postData:{"priceid":"${pricePlan.priceAdjPlanId}"},
                datatype: "json",
                autowidth: true,
                shrinkToFit : true,
            //    height: 270,
                multiselect: true,
                colNames: ['药品编码', '通用名',  '剂型', '规格', '转换系数', '单位', '材质', '生产企业','项目名称','采购限价', '新采购限价', '最高零售限价', '新最高零售限价','商品编码'],
                colModel: [
					{ name: 'drugCode', width: 100,align: 'center', sortable:false },
                    { name: 'drugName', width: 140,align: 'left', sortable:false },
                    { name: 'formName', width: 80 ,align: 'center', sortable:false },
                    { name: 'specName', width: 80 ,align: 'left', sortable:false },
                    { name: 'factor', width: 80,align: 'center', sortable:false },
                    { name: 'unit', width: 40 ,align: 'center', sortable:false },
					{ name: 'materialName', width: 80 ,align: 'center', sortable:false },
                    { name: 'compName', width: 180,align: 'left', sortable:false},
                    { name: 'projName', width: 180,align: 'left', sortable:false},
                    { name: 'proPriceLimit', width: 80, align: "right", sortable:false,
							formatter : function(val, opts, rowdata){
								return formatAmount(val, opts, rowdata);
							}
                    },
                    { name: 'currProPriceLimit', width: 80, align: "center", sortable:false, formatter : function(val, opts, rowdata) {
                    	var str = formatAmount(val, opts, rowdata);
                    	var sb = "<input type='text' maxlength='10' oninput=\"value=value.replace(/[^\\d{1,}\\.\\d{1,}|\\d{1,}]/g,'')\" id='newPurchasePrice"+rowdata.priceAdjPalnDetailId+"'  style='width:99%;text-align:right;' value='"+str+"' onchange='valuechange(this.id)'/>";
                   		return sb;
                    } },
                    { name: 'retailPriceLimit', width: 120, align: "right", sortable:false,
                    	formatter : function(val, opts, rowdata){
							return formatAmount(val, opts, rowdata);
						}	
                    },
                    { name: 'currRetailPriceLlimit', width: 120, align: "right", sortable:false, formatter : function(val, opts, rowdata) {
                    	var str = formatAmount(val, opts, rowdata);
                    	var sb = "<input type='text' maxlength='10' oninput=\"value=value.replace(/[^\\d{1,}\\.\\d{1,}|\\d{1,}]/g,'')\" id='newHighestRetailPrice"+rowdata.priceAdjPalnDetailId+"' style='width:99%;text-align:right;' value='"+str+"' onchange='valuechange(this.id)'/>";
                    	return sb;
                    } },
                    { name: 'goodsCode', width: 100,align: 'center', sortable:false,hidden:true }
           			
                ],
                rowNum: 20,
                rowList: [10, 20, 50, 100],
                rownumbers: true,
                pager: "#gridpage",
                viewrecords: true,
                caption: '${pricePlan.priceAdjPlanName} ( ${pricePlan.executeCatName} ${pricePlan.executeDateTimeStr} )',
                jsonReader: {
                    repeatitems: false,
                    id: "priceAdjPalnDetailId"
                },
                gridComplete:function(){
                    //序号列宽度自适应（参数为jqgridID）
                    autoRNWidth("gridlist");
                    //数据只有一条时默认选中（参数为jqgridID）
                    selectByOneData("gridlist");
                }
            });
            $("#gridlist").jqGrid('navGrid', '#gridpage', { add: false, edit: false, del: false, search: false, refresh: false });
            $(window).trigger("resize");
			$("#gridlist").jqGrid("setGridHeight",create());
        });
	
	
		function batchEditDrug() {
	    	var rowIds = $("#gridlist").jqGrid("getDataIDs")||[];
			if (rowIds.length <= 0) {
				$.HN.message.alert("请您添加调价明细！", "消息", "warn");
				return;
			}
			var list = [];
			var reg = new RegExp(/^[0-9]+(.[0-9]+)*$/);
			for (var i=0; i<rowIds.length; i++) {
				rowId = rowIds[i];
				var proPriceLimit = $.trim($("#gridlist").jqGrid("getRowData",rowId).proPriceLimit);
				var currProPriceLimit = $.trim($("#newPurchasePrice"+rowId).val());
				if (currProPriceLimit == null || currProPriceLimit == "") {
					$.HN.message.alert("请输入新采购限价！", "消息", "warn");
					return;
				}
				if(!reg.test(currProPriceLimit)){
					$.HN.message.alert("采购限价必须是数字！", "消息", "warn");
					return;
				}
				var index = currProPriceLimit.lastIndexOf(".");
	            if (index > 0 && currProPriceLimit.substr(index).length > 3) {
	                $.HN.message.alert("采购限价最多保留两位小数！请重新输入", "消息", "warn");
	                return false;
	            }
	            if(parseFloat(proPriceLimit)<=parseFloat(currProPriceLimit)){
	            	 $.HN.message.alert("新采购价必须小于采购限价！", "消息", "warn");
		                return false;
	            }
				var retailPriceLimit = $.trim($("#gridlist").jqGrid("getRowData",rowId).retailPriceLimit);
				var currRetailPriceLlimit = $.trim($("#newHighestRetailPrice"+rowId).val());
				if (currRetailPriceLlimit == null || currRetailPriceLlimit == "") {
					$.alert("请输入新最高零售限价！","warn");
					return;
				}
				if(!reg.test(currRetailPriceLlimit)){
					$.HN.message.alert("最高零售限价必须是数字！", "消息", "warn");
					return;
				}
				var index = currRetailPriceLlimit.lastIndexOf(".");
                if (index > 0 && currRetailPriceLlimit.substr(index).length > 3) {
                    $.HN.message.alert("最高零售价最多保留两位小数！请重新输入", "消息", "warn");
                    return false;
                }
                if(parseFloat(retailPriceLimit)<=parseFloat(currRetailPriceLlimit)){
	            	 $.HN.message.alert("新最高零售限价必须小于最高零售价！", "消息", "warn");
		                return false;
	            }
				
				list.push({
					"priceAdjPalnDetailId":rowId, 
					"currProPriceLimit": currProPriceLimit,
					"currRetailPriceLlimit": currRetailPriceLlimit
				});
			}
			$.HN.message.confirm("您确定保存吗？", "提示信息", "确定").on(function(bool) {
				if (bool) {
			       	$.ajax({
						type:"POST",
						url:"batchSubmitPlanDrugEdit.html",
						data:{"drugs":JSON.stringify(list)},
						dataType:"json",
						success:function(result){
							if (result.success) {
								sta = 0 ;
								search();
								$.HN.message.alert("为您保存成功！", "消息", "");
							} else {
			    				$.HN.message.alert("保存失败！", "消息", "error");
			    			}
						},
						error:function() {
							top.window.document.location = "${ctx}/login.html";
						}
					});
				}
			});
		}
		
		function batchDeleteDrug() {
			var rowIds = $("#gridlist").jqGrid("getGridParam", "selarrrow") || [];
			if (rowIds.length <= 0) {
				$.HN.message.alert("请您选择要删除的明细！", "消息", "warn");
				return;
			}
			var list = [];
			for (var i=0; i<rowIds.length; i++) {
				rowId = rowIds[i];
				list.push(rowId);
			}
			$.HN.message.confirm("您确定删除选中的调价明细吗？", "提示信息", "确定").on(function(bool) {
				if (bool) {
					$.post("batchDeleteDrug.html", {
		    			"drugs" : json.jsonToString(list)
		    		}, function(result) {
		    			if (result.success) {
		    				var curpage = $("#gridlist").jqGrid('getGridParam', 'page');
		    				search(curpage);
		    				$.HN.message.alert("为您成功删除"+result.operCount+"条明细！", "消息", "success");
		    			} else {
		    				$.HN.message.alert("操作失败！", "消息", "error");
		    			}
		    		}, "json").error(function(err) {
		    			top.window.document.location = "${ctx}/login.html"; 
		    		});
				}
			});
			
		}
		function valuechange(id){
			sta = 1;
		}
    </script>
</body>
</html>